package tasks;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.concurrent.Callable;

import tools.FileManager;
import core.Bdecoder;
import core.BeValue;
import core.Executor;
import core.Torrent;

public class ParseTorrent implements Callable<Torrent> {
	private String path;
	private File file;
	
	public ParseTorrent(String path) {
		this.path = path;
	}
	
	public ParseTorrent(File file) {
		this.file = file;
		this.path = this.file.getAbsolutePath();
	}
		
	@Override
	public Torrent call() throws Exception {
		FileManager fileManager = new FileManager(this.file);
        Bdecoder bdecoder = new Bdecoder((InputStream) fileManager.getByteArrayInputStream());
		bdecoder.set_special_map_name("info");		
		BeValue result = bdecoder.bdecode();			
		byte[] hashInfo = bdecoder.get_special_map_digest();
		
		Torrent torrent = new Torrent();		
		torrent.load(result);
		torrent.setHashInfo(hashInfo);	
		
		ArrayList<String> trackers = new ArrayList<String>();
		trackers.add(torrent.getAnnounce());
		trackers.addAll(torrent.getAnnounceList());
		
		Executor.getThreadPool().execute(new ContactTrackers(trackers, torrent));
		
		return torrent;
	}

}
